package com.example.yt_app.Activity.Device;


import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import com.example.yt_app.Activity.BaseActivity.SwipeBackBaseActivity;
import com.example.yt_app.AppManager;
import com.example.yt_app.R;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.SB_Parameter;
import com.example.yt_app.Urils.State;

import com.example.yt_app.Urils.Utils;
import com.example.yt_app.bean.HistoricalData.Datapoints;
import com.example.yt_app.bean.HistoricalData.Datastreams;
import com.example.yt_app.bean.HistoricalData.HistoricalJsonRootBean;
import com.example.yt_app.bean.Onenet.Data;
import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.example.yt_app.Urils.MPAndroidChartUrils.*;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.jaredrummler.materialspinner.MaterialSpinner;

import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 主页
 * Created by yangle on 2016/11/25.
 * <p>
 * Website：http://www.yangle.tech
 * GitHub：https://github.com/alidili
 * CSDN：http://blog.csdn.net/kong_gu_you_lan
 * JianShu：http://www.jianshu.com/u/34ece31cd6eb
 */

@SuppressWarnings("ALL")
public class LineChartActivity extends SwipeBackBaseActivity  {
    private OkHttpClient okHttpClient;
    @BindView(R.id.detail_toolbar)
    Toolbar toolbar;
    @BindView(R.id.spinner)
    MaterialSpinner spinner;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.online)
    TextView Online;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.temp)
    TextView Temp;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.hume)
    TextView Hume;
    /*画图*/
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.chart_tmp)
    LineChart Chart_tmp;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.chart_hum)
    LineChart Chart_hum;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.create_time)
    TextView Create_time;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.updatetime)
    TextView Updatetime;
    private ArrayList<Entry> tmp = new ArrayList<>();
    private ArrayList<Entry> hum = new ArrayList<>();
    private Handler mmHandler;
    private mHandler mHandler = new mHandler();
    private final ArrayList<Map<String, Object>>list = new ArrayList<>();
    private String online;
    private String responseData;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private String ID;
    private String name;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private String ONOFF;
    private String endtime;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private Date create_time;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private String create_t;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private String unit_symbol;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private Date update_at;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private String update_t;
    private String uuid;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private int current_value;

    int i=30;
    @Override
    protected SwipeBackLayout getSwipeBackLayout(int layoutId) {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_line_chart;
    }

    @Override
    protected void initView() {


        AppManager.getInstance().addActivity(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }


        /*温度湿度画图实例化*/
        ChartUtils.initChart(Chart_tmp);
        ChartUtils.initChart(Chart_hum);
        ChartUtils.notifyDataSetChanged(Chart_tmp, tmp, ChartUtils.dayValue);

        ChartUtils.notifyDataSetChanged(Chart_hum, hum, ChartUtils.dayValue);
        /*五秒跟新一次温湿度*/
        initMenu();

        HandlerThread thread = new HandlerThread("MyHandlerThread");
        thread.start();
        //创建一个HandlerThread并启动它
        mmHandler = new Handler(thread.getLooper());
        //使用HandlerThread的looper对象创建Handler，如果使用默认的构造方法，很有可能阻塞UI线程
        while (State.DHT11 == false ){
            mmHandler.post(mBackgroundRunnable);
            //将线程post到Handler中
            Delay.Delay_ms(300);
        }


    }
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @Override
    protected void initData() {
        okHttpClient = new OkHttpClient();
        Date date = new Date(System.currentTimeMillis());
        endtime = Utils.Endtime(Utils.dateToString(date,"yyyy-MM-ddHH:mm:ss"));
        Intent i =getIntent();
        ID= i.getStringExtra("id");
        online= i.getStringExtra("online");
        toolbar.setTitle(ID);
        Online.setText(online);
        //noinspection AlibabaUndefineMagicConstant
        if (online == "√"){
            //String o = String.valueOf(devices.get(i).getOnline());
            Online.setTextColor(Color.GREEN);
        }else {
            Online.setTextColor(Color.RED);
        }
        State.OTHER = false;

        toolbar.setTitle(i.getStringExtra("name"));
        GetInformation();
        Getdata();
        Delay.Delay_ms(200);

    }
    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(toolbar).init();
        //隐藏状态栏
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        ImmersionBar.with(this).titleBar(R.id.detail_toolbar).keyboardEnable(true).init();
    }
    private void initMenu() {

        spinner.setItems("今日", "本周", "本月");
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                switch (position) {
                    case 0:
                        // 更新图表
                        //ChartUtils.notifyDataSetChanged(Chart_tmp, getData(), position);
                        break;
                    case 1:
                        //ChartUtils.notifyDataSetChanged(Chart_tmp, Data(), position);
                        break;
                    case 2:
                        //ChartUtils.notifyDataSetChanged(Chart_tmp, dData(), position);
                        break;

                    default:
                        break;
                }

            }

        });

    }
    @SuppressWarnings("AliDeprecation")
    private class mHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Create_time.setText(create_t);
                    Updatetime.setText(update_t);
                    Temp.setText(list.get(0).get("current_value").toString());
                    Hume.setText(list.get(1).get("current_value").toString());
                    break;

                default:break;
            }
        }
    }
    @Override
    protected void setListener() {
        //toolbar返回按钮监听
        toolbar.setNavigationOnClickListener(v ->finish() );
    }
    Map<String, Object> map;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void GetInformation(){
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/" + ID + "/datastreams/" )
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);
        Observable.just(request)
                .subscribe(new Observer<Request>() {
                    //订阅成功
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        call.enqueue(new Callback() {
                            @SuppressWarnings("AlibabaUndefineMagicConstant")
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                try {

                                    responseData = response.body().string();
                                    System.out.println(responseData);
                                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
                                    List<Data> streams = (List<Data>) app.getData();
                                    update_at = streams.get(0).getUpdate_at();
                                    create_time = streams.get(0).getCreate_time();
                                    update_t = Utils.dateToString(update_at,"yyyy-MM-dd HH:mm:ss");
                                    create_t = Utils.dateToString(create_time,"yyyy-MM-dd HH:mm:ss");

                                    //noinspection AlibabaUndefineMagicConstant
                                    for (int i = 0; i < 2; i++) {
                                        map = new HashMap<>();
                                        map.put("current_value", streams.get(i).getCurrent_value());
                                        map.put("unit_symbol",streams.get(i).getUnit_symbol());
                                        list.add(map);
                                    }
                                    Message message = Message.obtain();
                                    message.what = 1;
                                    mHandler.sendMessage(message);

                                } catch (IOException e){
                                    e.printStackTrace();
                                }
                            }
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                            }

                        });
                    }
                    //上层给我的相应

                    @Override
                    public void onNext(@NotNull Request request) {
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                    //连接思维发生异常

                    @Override
                    public void onError(@NotNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void Getdata(){
        /**
         * 函数：sort
         * 时间排序方式，DESC：倒序，ASC：升序，默认为ASC
         * */
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/"+ID+"/datapoints?"
                        +"end="+ endtime+"&"+
                        "start="+"2021-06-02T08:06:30"+"&"+
                        "sort=" +"DESC"+"&"+
                        "datastream_id=" +"temp,humi"
                )
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant"})
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {

                    String responseData = response.body().string();
                    Log.i("TAG" , "postAsync" + responseData);
                    HistoricalJsonRootBean historicalJsonRootBean = Json.gson.fromJson(responseData, HistoricalJsonRootBean.class);
                    SB_Parameter.HISTORYLIST = historicalJsonRootBean.getData().getCount();
                    if (SB_Parameter.HISTORYLIST>0){
                        List<Datastreams> data = (List<Datastreams>) historicalJsonRootBean.getData().getDatastreams();
                        List<Datapoints> temp = (List<Datapoints>) data.get(0).getDatapoints();
                        List<Datapoints> hume = (List<Datapoints>) data.get(1).getDatapoints();
                        System.out.println(historicalJsonRootBean.getData().getCount());
                        //System.out.println(data.get(0).getDatapoints().get(0).getValue());

                        //noinspection AlibabaUndefineMagicConstant
                        for (int i = 0; i < 7; i++){
                            float T = Float.parseFloat(temp.get(i).getValue());
                            float H = Float.parseFloat(hume.get(i).getValue());
                            tmp.add(i,new Entry(i, T));
                            hum.add(i,new Entry(i, H));

                        }
                        State.DHT11 = true;
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
        });
    }
    @SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant"})
    private  List<Entry> DataTmp() {
        tmp.set(0,new Entry(0, tmp.get(1).getY()));
        tmp.set(1,new Entry(1, tmp.get(2).getY()));
        tmp.set(2,new Entry(2, tmp.get(3).getY()));
        tmp.set(3,new Entry(3, tmp.get(4).getY()));
        tmp.set(4,new Entry(4, tmp.get(5).getY()));
        tmp.set(5,new Entry(5, tmp.get(6).getY()));
        //noinspection AlibabaUndefineMagicConstant,AlibabaUndefineMagicConstant
        if (tmp.get(6).getY()>30){
            tmp.set(6,new Entry(6, tmp.get(6).getY()-5));
        }else {
            tmp.set(6,new Entry(6, tmp.get(6).getY()+1));
        }


        return tmp;
    }

    private List<Entry> getDataTmp() {

        tmp.add(0,new Entry(0, 15));
        tmp.add(1,new Entry(1, 7));
        tmp.add(2,new Entry(2, 20));
        tmp.add(3,new Entry(3, 8));
        tmp.add(4,new Entry(4, 6));
        tmp.add(5,new Entry(5, 15));
        tmp.add(6,new Entry(6, 50));

        return tmp;
    }
    private List<Entry> getDataHum() {

        hum.add(0,new Entry(0, 15));
        hum.add(1,new Entry(1, 7));
        hum.add(2,new Entry(2, 20));
        hum.add(3,new Entry(3, 8));
        hum.add(4,new Entry(4, 6));
        hum.add(5,new Entry(5, 15));
        hum.add(6,new Entry(6, 50));

        return hum;
    }
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    private  List<Entry> DataHum() {
        hum.set(0,new Entry(0, hum.get(1).getY()));
        hum.set(1,new Entry(1, hum.get(2).getY()));
        hum.set(2,new Entry(2, hum.get(3).getY()));
        hum.set(3,new Entry(3, hum.get(4).getY()));
        hum.set(4,new Entry(4, hum.get(5).getY()));
        hum.set(5,new Entry(5, hum.get(6).getY()));
        hum.set(6,new Entry(6, hum.get(6).getY()+1));

        return hum;
    }

    //实现耗时操作的线程
    Runnable mBackgroundRunnable = new Runnable() {

        @Override
        public void run() {

            //----------模拟耗时的操作，开始---------------
            while(State.DHT11) {
                    ChartUtils.notifyDataSetChanged(Chart_tmp, DataTmp(), ChartUtils.dayValue);
                    ChartUtils.notifyDataSetChanged(Chart_hum, DataHum(), ChartUtils.dayValue);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //----------模拟耗时的操作，结束---------------
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁线程
        mmHandler.removeCallbacks(mBackgroundRunnable);
        State.DHT11 =false;
    }
    @Override
    protected void onStop() {
        super.onStop();
        State.DHT11 = false;
    }
}
